//
//  FeedbackController.m
//  TouGuApp
//
//  Created by tianshikechuang on 16/6/21.
//  Copyright © 2016年 tianshikechuang. All rights reserved.
//

#import "FeedbackController.h"
#import "TextView.h"
#import "ScrollView.h"
#import "UIButton+Block.h"
#import "XMNPhotoPickerKit.h"
#import "XMNPhotoCollectionController.h"
#import "XMNPhotoPreviewController.h"
#import "XMNAssetCell.h"
#import "commViewController.h"
#import "pureTextViewController.h"
#import "ZYQiniuTool.h"
#import "FeedbackController.h"


#define urlQiNiuYun @"http://oamepd39m.bkt.clouddn.com"

@interface FeedbackController ()<UITextViewDelegate,UICollectionViewDelegate,UICollectionViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
{
    
}
@property(nonatomic, strong) TextView * textView;
@property(nonatomic, strong) ScrollView * scrollView;
@property(nonatomic, weak) UIButton * rigth;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSArray * images;
@property (nonatomic, strong) NSArray * arr;

@property (nonatomic, strong) UIButton *anonymous;
@property (nonatomic, strong) NSString *token;

@property (nonatomic, strong) NSString *imageUrls;

@end

@implementation FeedbackController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"信息反馈";
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:self.textView];

    UIButton * rightItem = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 64, 44)];
    self.rigth = rightItem;
    rightItem.userInteractionEnabled=NO;
    rightItem.selected = YES;
    
    [rightItem setTitle:@"提交" forState:UIControlStateNormal];
    [rightItem setTitleColor:[UIColor grayColor] forState:UIControlStateSelected];
    [rightItem addBlockForControlEvents:UIControlEventTouchUpInside block:^(id sender) {
       
        [self uploadToQiNiuYun];
        
    }];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightItem];
 
    [self addcollcionView];
    
    
    [self getToken];
}

- (void)getToken{
    
    [NetWorkingTool POST:@"token/getUploadToken" parameters:nil success:^(id responseObject, NSError *error) {
        NSLog(@"----token/getUploadToken---%@--%@",responseObject,error);
        self.token = [responseObject objectForKey:@"uploadToken"];

    } failure:^(id responseObject, NSError *error) {
        NSLog(@"----token/getUploadToken--%@--%@",responseObject,error);

    }];
    
}


- (void)uploadToQiNiuYun{
    
    if (self.images.count <= 0) {
        
        [self postAd];
        
        return;
    }
    
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    NSMutableArray * arr = [NSMutableArray array];
    for (UIImage * image in self.images) {
        NSString * key = [NSString stringWithFormat:@"%dkey%.0f.png",rand(),[NSDate timeIntervalSinceReferenceDate]];
        
        NSString *token = self.token;
        QNUploadManager *upManager = [[QNUploadManager alloc] init];
        NSData *data = UIImageJPEGRepresentation(image,0.8);
        [upManager putData:data key:key token:token
                  complete: ^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
                      
                      NSLog(@"info : %@", resp);
                      
                      [MBProgressHUD hideHUDForView:self.view animated:YES];
                      if (!info.error || [[info.error description] isEqualToString:@"(null)"] || [info.error isKindOfClass:[NSNull class]]) {
                          NSString * imageKey = [resp objectForKey:@"key"];
                          NSString * imageUrl = [urlQiNiuYun stringByAppendingPathComponent:imageKey];
//                          NSString * imageUrls = [imageUrl stringByAppendingString:@".png"];
                          [arr addObject:imageUrl];
                          
                          
                          if (arr.count == self.images.count) {
                              
                              
                              
                              self.imageUrls = [arr componentsJoinedByString:@","];
                              [self postAd];
                              
                          }
                      }else{
                          [MBProgressHUD showError:[info.error description]];
                      }
                      
                      
                  } option:nil];
        
    }
//    /16807key491673352
    
  
    
    
}

- (void)postAd{
    /*
     u_id	String	发帖子用户ID
     pt_url	String	帖子地址
     p_date	String	发帖时间
     p_content	String	帖子标题
     p_type	String	帖子类型
     */
    NSMutableDictionary * dic = [NSMutableDictionary dictionary];
    
    dic[@"u_id"] = [UserModel sharedUserModel].u_id;
    dic[@"pt_url"]= self.imageUrls?self.imageUrls:@"";
    dic[@"p_date"] = [Tools MM_dd_HH_mm_ssWithDate:[NSDate date]];
    dic[@"p_content"] = [Tools utf8ToUnicode:self.textView.text];
    dic[@"p_type"] = @"0";
    
    [NetWorkingTool POST:@"post/postAdd" parameters:dic success:^(id responseObject, NSError *error) {
        NSLog(@"----post/postAd---%@--%@",responseObject,error);
        
        [MBProgressHUD showSuccess:[responseObject objectForKey:@"mes"]];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.navigationController popToRootViewControllerAnimated:YES];
        });
//    http:/oamepd39m.bkt.clouddn.com/1144108930key491710117
//    http:/oamepd39m.bkt.clouddn.com/470211272key491710117
//    http:/oamepd39m.bkt.clouddn.com/282475249key491710117,http:/oamepd39m.bkt.clouddn.com/1458777923key491710117,http:/oamepd39m.bkt.clouddn.com/1457850878key491710117,http:/oamepd39m.bkt.clouddn.com/984943658key491710117,http:/oamepd39m.bkt.clouddn.com/16807key491710117,http:/oamepd39m.bkt.clouddn.com/1622650073key491710117,http:/oamepd39m.bkt.clouddn.com/101027544key491710117,
        
    } failure:^(id responseObject, NSError *error) {
        NSLog(@"----post/postAd--%@--%@",responseObject,error);
        
        [MBProgressHUD showError:[error description]];
//        [MBProgressHUD hideHUD];
    }];
    
}



- (TextView *)textView{
    if (!_textView) {
        _textView = [[TextView alloc] initWithFrame:CGRectMake(0, 64, KScreenWidth, 160)];
        _textView.font = [UIFont systemFontOfSize:16];
        _textView.maxCount = 500;
        _textView.placeholder = @"请输入帖子的内容...";
        __block typeof(self) weakSelf = self;
        [_textView setEditBlock:^(NSString *str) {
            if (str.length < 1) {
                weakSelf.rigth.userInteractionEnabled = NO;
                weakSelf.rigth.selected = YES;
            }else{
                weakSelf.rigth.userInteractionEnabled = YES;
//                weakSelf.rigth.selected = NO;
            }
        }];
        
        [self.view addSubview:[[UIView alloc] initWithFrame:CGRectZero]];
    }
    return _textView;
}



- (void)addcollcionView{
    
    UICollectionViewFlowLayout * fl = [[UICollectionViewFlowLayout alloc] init];
    CGFloat width = (KScreenWidth - 70)/3;
    fl.itemSize = CGSizeMake(width, width);
    fl.minimumLineSpacing = 5;
    fl.minimumInteritemSpacing = 5;
    
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(25, 224, KScreenWidth - 50, KScreenWidth - 50) collectionViewLayout:fl];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    
    [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"CellWithReuseId"];
    [self.view addSubview:self.collectionView];
    
    //匿名按钮
    UIButton * anonymous =  [[UIButton alloc]init];
    anonymous.backgroundColor = [UIColor blackColor];
    [anonymous setTitle:@"匿名发送" forState:UIControlStateNormal];
    anonymous.frame = CGRectMake(25, 224 + width, 100, 20);
    
    [self.view addSubview:anonymous];
    self.anonymous = anonymous;
    
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
        NSLog(@"%@ -- %d",self.images,(int)self.images.count);
        
        CGFloat height;
        if (self.images.count < 3) {
            
            height = (KScreenWidth - 70)/3 + 10;
            
        }else if (self.images.count < 6){
            height = (KScreenWidth - 70)/3 * 2 + 15;
            
        }else{
            
            height = (KScreenWidth - 70) + 20;
        }
        
        height = height + collectionView.frame.origin.y;
        self.anonymous.frame = CGRectMake(25, height, 100, 20);
        
        return self.images.count>=9?self.images.count:self.images.count + 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
        UICollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CellWithReuseId" forIndexPath:indexPath];
    
//    cell.backgroundColor = [UIColor redColor];
        UIImageView * imageview = [[UIImageView alloc] initWithFrame:cell.bounds];
    [cell.contentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
        if (self.images.count < 9) {
            if (indexPath.row == 0) {
                
                // 这里设置加号按钮的图片
                imageview.image = [UIImage imageNamed:@"tianjiazp"];
                [cell.contentView addSubview:imageview];
                
                return cell;
            }else{
                imageview.image = self.images[indexPath.row -1];
                [cell.contentView addSubview:imageview];
            }
        }else{
            imageview.image = self.images[indexPath.row];
            [cell.contentView addSubview:imageview];
        }
    
    
    return cell;
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == 0 && self.images.count < 9) {
        
        [UIAlertController showSheetViewWithTitle:@"温馨提示" message:@"" isCancle:@"取消" sureTitle:@"照相机" suerAction:^(UIAlertAction *action) {
            
            UIImagePickerController * imagePicker = [[UIImagePickerController alloc] init];
            imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
            imagePicker.delegate = self;
            
            [self presentViewController:imagePicker animated:YES completion:nil];
    
        } otherTitles:@[@"图库选择"] otherActions:^(UIAlertAction *action) {
            //1.初始化一个XMNPhotoPickerController
            NSInteger maxCount = 9 - self.images.count;
            
            XMNPhotoPickerController *photoPickerC = [[XMNPhotoPickerController alloc] initWithMaxCount:maxCount delegate:nil];
            
            //3..设置选择完照片的block 回调
            __weak typeof(self) wSelf = self;
            [photoPickerC setDidFinishPickingPhotosBlock:^(NSArray<UIImage *> *images, NSArray<XMNAssetModel *> *assets) {
                __weak typeof(*&self) self = wSelf;
                NSMutableArray * totol = [NSMutableArray arrayWithArray:self.arr];
                [totol addObjectsFromArray:assets];
                self.arr = totol;
                NSMutableArray * arr = [NSMutableArray array];
                for (XMNAssetModel * model in totol) {
                    [arr addObject:model.thumbnail];
                }
                self.images = arr;
                
                [self dismissViewControllerAnimated:YES completion:nil];
                [self.collectionView reloadData];
            }];
            
            [self presentViewController:photoPickerC animated:YES completion:nil];
        }, nil];
        
    }else{
        
        return;
        
        NSInteger index = self.images.count >= 9?indexPath.row:indexPath.row - 1;
        
        XMNPhotoPreviewController *previewC = [[XMNPhotoPreviewController alloc] initWithCollectionViewLayout:[XMNPhotoPreviewController photoPreviewViewLayoutWithSize:[UIScreen mainScreen].bounds.size]];
        previewC.assets = self.arr;
        previewC.selectedAssets = [NSMutableArray arrayWithArray:self.arr];
        previewC.currentIndex = index;
        previewC.maxCount = self.arr.count;
        
        [previewC setDidFinishPreviewBlock:^(NSArray<XMNAssetModel *> *selectedAssets) {
            self.arr = selectedAssets;
            NSMutableArray * arr = [NSMutableArray array];
            for (XMNAssetModel * model in selectedAssets) {
                [arr addObject:model.thumbnail];
            }
            self.images = arr;
            [self.collectionView reloadData];
        }];
        __block typeof(previewC) blockP = previewC;
        [previewC setDidFinishPickingBlock:^(NSArray<UIImage *> *images, NSArray<XMNAssetModel *> *selectedAssets) {
            
            self.arr = selectedAssets;
            NSMutableArray * arr = [NSMutableArray array];
            for (XMNAssetModel * model in selectedAssets) {
                [arr addObject:model.thumbnail];
            }
            self.images = arr;
            
            [blockP.navigationController popViewControllerAnimated:YES];
            
            [self.collectionView reloadData];
        }];
        [self.navigationController pushViewController:previewC animated:YES];
        
    }
    
    
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
        [picker dismissViewControllerAnimated:YES completion:nil];
        
        NSLog(@"%@",info[UIImagePickerControllerOriginalImage]);
        
        NSMutableArray * mArr = [NSMutableArray array];
        [mArr addObjectsFromArray:self.images];
        [mArr addObject:info[UIImagePickerControllerOriginalImage]];
        
        self.images = mArr;
        [self.collectionView reloadData];
}







@end
